<template>
    <div class="container">
        <div class="card" v-watermark="watermarkOptions">
            阿斯卡佳都科技阿迪萨科技大刷卡机
        </div>
        <div style="width: fit-content" v-watermark="watermarkOptions">
            <img src="@/assets/images/jita.jpg" width="300" alt="" />
        </div>

        <h3>图片上加文字</h3>
        <div>
            <input type="file" accept="image/*" @change="handleFileChange" />
            <br />
            <el-input
                type="text"
                v-model="text"
                placeholder="输入要添加的文字"
				@change="drawImage"
            />
            <br />
            <img :src="imageUrl" width="500" alt="处理后的图片" />
        </div>
    </div>
</template>

<script setup>
    import { onMounted, ref } from "vue";

    const watermarkOptions = ref({
        text: "版权所有",
        font: "Arial",
        color: "red",
        fontSize: 14,
        rotate: 30,
        opacity: 0.5,
    });

    const text = ref("");
    const imageUrl = ref("");
    const canvasEl = ref(null);
    const canvasContext = ref(null);
    const imgRsc = ref('');

    const handleFileChange = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
		reader.onload = (event) => {
			imgRsc.value = event.target.result;
            drawImage();
        };
        reader.readAsDataURL(file);
    };
    const drawImage = () => {
        const img = new Image();
        img.src = imgRsc.value;
        img.onload = () => {
            canvasEl.value.width = img.width;
            canvasEl.value.height = img.height;
            canvasContext.value.drawImage(img, 0, 0);

            drawImageWithText();
            updateImageUrl();
        };
    };
    const drawImageWithText = () => {
        if (!canvasContext.value) return;

        canvasContext.value.fillStyle = "#ff0000"; // 文字颜色
        canvasContext.value.font = "200px Arial"; // 字体和大小
        const txt = text.value || "请输入文字";
        const x = 10; // 距离左边 10 像素
        const y = canvasEl.value.height - 100; // 距离底部 20 像素
        canvasContext.value.fillText(txt, x, y); // 文字位置
    };
    const updateImageUrl = () => {
        const canvas = canvasEl.value;
        const imgURL = canvas.toDataURL();
        imageUrl.value = imgURL;
    };
    onMounted(() => {
        canvasEl.value = document.createElement("canvas");
        canvasContext.value = canvasEl.value.getContext("2d");
    });
</script>
<style lang="less" scoped>
    .container {
        .card {
            margin-bottom: 10px;
            padding: 10px;
            width: 400px;
            height: 200px;
            border: 1px solid #eee;
            box-shadow: 3px 3px 3px #eee;
            border-radius: 4px;
        }
    }
</style>
